<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    
    <title>Pony 教程  | 流程控制（Control Structures）</title>
    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">

    <meta name="viewport" content="width=device-width,minimum-scale=1">
    <meta name="generator" content="Hugo 0.69.0-DEV" />
    
    
      <META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
    

    <style>
      @font-face {
        font-family: 'Icon';
        src: url('/pony-tutorial/dist/fonts/icon.eot?52m981');
        src: url('/pony-tutorial/dist/fonts/icon.eot?#iefix52m981')
               format('embedded-opentype'),
             url('/pony-tutorial/dist/fonts/icon.woff?52m981')
               format('woff'),
             url('/pony-tutorial/dist/fonts/icon.ttf?52m981')
               format('truetype'),
             url('/pony-tutorial/dist/fonts/icon.svg?52m981#icon')
               format('svg');
        font-weight: normal;
        font-style: normal;
      }
    </style>

    <link href="/pony-tutorial/dist/css/app.css" rel="stylesheet">
    <link href="/pony-tutorial/dist/css/highlight.css" rel="stylesheet">
    <link href="/pony-tutorial/dist/css/icon.css" rel="stylesheet">
    <link href="/pony-tutorial/dist/css/pony.css" rel="stylesheet">

    

    
      
    

    

    <meta property="og:title" content="流程控制（Control Structures）" />
<meta property="og:description" content="在程序开发过程中，你需要能够对条件做出判断，对集合进行遍历，或者重复执行一些逻辑。因此，流程控制必不可少。Pony具有你在其他语言中所熟悉的流程控制控制，例如if，while和for，但是在Pony中，它们的工作方式略有不同。
条件判断（Conditionals） if是最简单的流程控制控制。它仅在条件为真时才允许您执行某些操作。在Pony中的用法：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) end 可以像在C语言中那样使用整数和指针作为条件吗？ 不行。在Pony中，if条件必须是布尔类型，即条件的返回值值始终为true或false。如果要判断数字a是否不为0，则需要明确的使用a！= 0。这个限制让Pony程序避免了潜在的类型错误。
需要在条件失败时的执行一些逻辑，只需添加一个else：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;a is not bigger&quot;) end 通常，您想要检测和处理多种条件，可以嵌套if语句，但这有点丑陋：
if a == b then env.out.print(&quot;they are the same&quot;) else if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;b bigger&quot;) end end 作为替代方案，Pony提供了结合了else和if的elseif关键字。这与其他语言中else if相同，并且每个if可以有任意数量的elseif：
if a == b then env.out.print(&quot;they are the same&quot;) elseif a &gt; b then env." />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://damon-kwok.github.io/pony-tutorial/expressions/control-structures.html" />
<meta property="article:modified_time" content="2020-04-17T18:23:30+08:00" />
<meta itemprop="name" content="流程控制（Control Structures）">
<meta itemprop="description" content="在程序开发过程中，你需要能够对条件做出判断，对集合进行遍历，或者重复执行一些逻辑。因此，流程控制必不可少。Pony具有你在其他语言中所熟悉的流程控制控制，例如if，while和for，但是在Pony中，它们的工作方式略有不同。
条件判断（Conditionals） if是最简单的流程控制控制。它仅在条件为真时才允许您执行某些操作。在Pony中的用法：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) end 可以像在C语言中那样使用整数和指针作为条件吗？ 不行。在Pony中，if条件必须是布尔类型，即条件的返回值值始终为true或false。如果要判断数字a是否不为0，则需要明确的使用a！= 0。这个限制让Pony程序避免了潜在的类型错误。
需要在条件失败时的执行一些逻辑，只需添加一个else：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;a is not bigger&quot;) end 通常，您想要检测和处理多种条件，可以嵌套if语句，但这有点丑陋：
if a == b then env.out.print(&quot;they are the same&quot;) else if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;b bigger&quot;) end end 作为替代方案，Pony提供了结合了else和if的elseif关键字。这与其他语言中else if相同，并且每个if可以有任意数量的elseif：
if a == b then env.out.print(&quot;they are the same&quot;) elseif a &gt; b then env.">
<meta itemprop="dateModified" content="2020-04-17T18:23:30&#43;08:00" />
<meta itemprop="wordCount" content="431">



<meta itemprop="keywords" content="" /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="流程控制（Control Structures）"/>
<meta name="twitter:description" content="在程序开发过程中，你需要能够对条件做出判断，对集合进行遍历，或者重复执行一些逻辑。因此，流程控制必不可少。Pony具有你在其他语言中所熟悉的流程控制控制，例如if，while和for，但是在Pony中，它们的工作方式略有不同。
条件判断（Conditionals） if是最简单的流程控制控制。它仅在条件为真时才允许您执行某些操作。在Pony中的用法：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) end 可以像在C语言中那样使用整数和指针作为条件吗？ 不行。在Pony中，if条件必须是布尔类型，即条件的返回值值始终为true或false。如果要判断数字a是否不为0，则需要明确的使用a！= 0。这个限制让Pony程序避免了潜在的类型错误。
需要在条件失败时的执行一些逻辑，只需添加一个else：
if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;a is not bigger&quot;) end 通常，您想要检测和处理多种条件，可以嵌套if语句，但这有点丑陋：
if a == b then env.out.print(&quot;they are the same&quot;) else if a &gt; b then env.out.print(&quot;a is bigger&quot;) else env.out.print(&quot;b bigger&quot;) end end 作为替代方案，Pony提供了结合了else和if的elseif关键字。这与其他语言中else if相同，并且每个if可以有任意数量的elseif：
if a == b then env.out.print(&quot;they are the same&quot;) elseif a &gt; b then env."/>

  </head>

  <body class="ma0 avenir bg-near-white">

    

  <header>
    <div class="bg-pony-brown">
      <nav class="pv3 ph3 ph4-ns" role="navigation">
  <div class="flex-l justify-between items-center center">
    <a href="https://damon-kwok.github.io/pony-tutorial/" class="f3 fw2 hover-white no-underline white-90 dib">
      Pony 教程
    </a>
    <div class="flex-l items-center">
      
      
<div hidden>
  <span id="new-window-0">Opens in a new window</span>
  <span id="new-window-1">Opens an external site</span>
  <span id="new-window-2">Opens an external site in a new window</span>
</div>



<a href="https://www.twitter.com/ponylang" target="_blank" class="link-transition twitter link dib z-999 pt3 pt0-l mr1" title="Twitter link" rel="noopener" aria-describedby="new-window-0">
  <svg height="32px"  style="enable-background:new 0 0 67 67;" version="1.1" viewBox="0 0 67 67" width="32px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M37.167,22.283c-2.619,0.953-4.274,3.411-4.086,6.101  l0.063,1.038l-1.048-0.127c-3.813-0.487-7.145-2.139-9.974-4.915l-1.383-1.377l-0.356,1.017c-0.754,2.267-0.272,4.661,1.299,6.271  c0.838,0.89,0.649,1.017-0.796,0.487c-0.503-0.169-0.943-0.296-0.985-0.233c-0.146,0.149,0.356,2.076,0.754,2.839  c0.545,1.06,1.655,2.097,2.871,2.712l1.027,0.487l-1.215,0.021c-1.173,0-1.215,0.021-1.089,0.467  c0.419,1.377,2.074,2.839,3.918,3.475l1.299,0.444l-1.131,0.678c-1.676,0.976-3.646,1.526-5.616,1.568  C19.775,43.256,19,43.341,19,43.405c0,0.211,2.557,1.397,4.044,1.864c4.463,1.377,9.765,0.783,13.746-1.568  c2.829-1.673,5.657-5,6.978-8.221c0.713-1.716,1.425-4.851,1.425-6.354c0-0.975,0.063-1.102,1.236-2.267  c0.692-0.678,1.341-1.419,1.467-1.631c0.21-0.403,0.188-0.403-0.88-0.043c-1.781,0.636-2.033,0.551-1.152-0.402  c0.649-0.678,1.425-1.907,1.425-2.267c0-0.063-0.314,0.042-0.671,0.233c-0.377,0.212-1.215,0.53-1.844,0.72l-1.131,0.361l-1.027-0.7  c-0.566-0.381-1.361-0.805-1.781-0.932C39.766,21.902,38.131,21.944,37.167,22.283z M33,64C16.432,64,3,50.569,3,34S16.432,4,33,4  s30,13.431,30,30S49.568,64,33,64z" style="fill-rule:evenodd;clip-rule:evenodd;fill:;"/></svg>

<span class="new-window"><svg  height="8px"  style="enable-background:new 0 0 1000 1000;" version="1.1" viewBox="0 0 1000 1000" width="8px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
<path d="M598 128h298v298h-86v-152l-418 418-60-60 418-418h-152v-86zM810 810v-298h86v298c0 46-40 86-86 86h-596c-48 0-86-40-86-86v-596c0-46 38-86 86-86h298v86h-298v596h596z" style="fill-rule:evenodd;clip-rule:evenodd;fill:;"/>
</svg>
</span></a>





<a href="https://github.com/damon-kwok/pony-tutorial-zh_CN" target="_blank" class="link-transition github link dib z-999 pt3 pt0-l mr1" title="Github link" rel="noopener" aria-describedby="new-window-0">
  <svg  height="32px"  style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" width="32px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
  <path d="M256,32C132.3,32,32,134.8,32,261.7c0,101.5,64.2,187.5,153.2,217.9c11.2,2.1,15.3-5,15.3-11.1   c0-5.5-0.2-19.9-0.3-39.1c-62.3,13.9-75.5-30.8-75.5-30.8c-10.2-26.5-24.9-33.6-24.9-33.6c-20.3-14.3,1.5-14,1.5-14   c22.5,1.6,34.3,23.7,34.3,23.7c20,35.1,52.4,25,65.2,19.1c2-14.8,7.8-25,14.2-30.7c-49.7-5.8-102-25.5-102-113.5   c0-25.1,8.7-45.6,23-61.6c-2.3-5.8-10-29.2,2.2-60.8c0,0,18.8-6.2,61.6,23.5c17.9-5.1,37-7.6,56.1-7.7c19,0.1,38.2,2.6,56.1,7.7   c42.8-29.7,61.5-23.5,61.5-23.5c12.2,31.6,4.5,55,2.2,60.8c14.3,16.1,23,36.6,23,61.6c0,88.2-52.4,107.6-102.3,113.3   c8,7.1,15.2,21.1,15.2,42.5c0,30.7-0.3,55.5-0.3,63c0,6.1,4,13.3,15.4,11C415.9,449.1,480,363.1,480,261.7   C480,134.8,379.7,32,256,32z"/>
</svg>

<span class="new-window"><svg  height="8px"  style="enable-background:new 0 0 1000 1000;" version="1.1" viewBox="0 0 1000 1000" width="8px" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >
<path d="M598 128h298v298h-86v-152l-418 418-60-60 418-418h-152v-86zM810 810v-298h86v298c0 46-40 86-86 86h-596c-48 0-86-40-86-86v-596c0-46 38-86 86-86h298v86h-298v596h596z" style="fill-rule:evenodd;clip-rule:evenodd;fill:;"/>
</svg>
</span></a>



    </div>
  </div>
</nav>

    </div>
  </header>


    <main role="main">
      
  <article class="w-100 ph4 pb5 pb6-ns pt1 pt3-ns">
    <div class="order-0 w-20 dn db-l doc-menu" id="doc-menu">
      <div class="order-0 w-20 mt2 mb2" id="search-wrapper">
  <input id="search-box" type="search" placeholder="search" />
</div>

      
<nav role="navigation">
  <ul class="list pa0 nl2">
    
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".getting-started">入门（Getting Started）</a>
        <ul class="getting-started desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/getting-started.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/getting-started/what-you-need.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              准备工作（What You Need）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/getting-started/hello-world.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Hello World
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/getting-started/how-it-works.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              庖丁解牛
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".types">类型系统（Types）</a>
        <ul class="types desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/types.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/at-a-glance.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              类型系统概览
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/classes.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              类（Classes）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/primitives.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              基元类（Primitives）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/actors.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              并发单元（Actors）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/traits-and-interfaces.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              特征和接口（Traits and Interfaces）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/structs.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              结构体（Structs）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/type-aliases.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              类型别名（Type Aliases）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/types/type-expressions.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              类型表达式（Type Expressions）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2  primary-color" data-target=".expressions">表达式（Expressions）</a>
        <ul class="expressions desktopmenu animated fadeIn list pl0 bg-light-gray db">
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/literals.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              字面量（Literals）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/variables.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              变量（Variables）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/ops.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              运算符（Operators）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/arithmetic.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              算术运算符（Arithmetic）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/control-structures.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 primary-color ">
              流程控制（Control Structures）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/methods.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              方法（Methods）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/errors.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              异常处理（Errors）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/equality.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              比较（Equality in Pony）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/sugar.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              语法糖（Sugar）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/object-literals.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              匿名对象（Object Literals）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/expressions/partial-application.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              柯里化（Partial Application）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".reference-capabilities">引用权能（Reference Capabilities）</a>
        <ul class="reference-capabilities desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/reference-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              引用权能（Reference Capabilities）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/guarantees.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能约束（Reference Capability Guarantees）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/consume-and-destructive-read.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能转让和破坏性读取（Consume and Destructive Read）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/recovering-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能借用（Recovering Capabilities）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/aliasing.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              别名引用（Aliasing）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/passing-and-sharing.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Passing and Sharing References
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/capability-subtyping.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能包含关系（Capability Subtyping）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/combining-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能合并（Combining Capabilities）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/arrow-types.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              箭头的用法（Arrow Types aka Viewpoints）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/reference-capabilities/capability-matrix.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              权能矩阵（Reference Capability Matrix）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".object-capabilities">对象权能模型（Object Capabilities）</a>
        <ul class="object-capabilities desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/object-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/object-capabilities/object-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              对象权能模型（Object Capabilities）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/object-capabilities/trust-boundary.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              边界信任（Trust Boundary）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".pattern-matching">模式匹配（Pattern Matching）</a>
        <ul class="pattern-matching desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/pattern-matching.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/pattern-matching/match.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              匹配表达式（Match Expressions）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/pattern-matching/as.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              as操作符（As Operator）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".generics">泛型（Generics）</a>
        <ul class="generics desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/generics.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/generics/generics-and-reference-capabilities.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              泛型和引用权能（Generics and Reference Capabilities）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/generics/generic-constraints.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              泛型约束（Constraints）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".packages">包（Packages）</a>
        <ul class="packages desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/packages.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/packages/package-system.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              包机制（Package System）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/packages/use-statement.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              包的使用方式（Use Statement）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/packages/standard-library.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              标准库（Standard Library）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".testing">测试（Testing）</a>
        <ul class="testing desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/testing.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/testing/ponytest.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Testing with Ponytest
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".c-ffi">C FFI</a>
        <ul class="c-ffi desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/c-ffi.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/c-ffi/calling-c.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Calling C from Pony
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/c-ffi/linking-c.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Linking to C Libraries
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/c-ffi/c-abi.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              C ABI
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/c-ffi/callbacks.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Callbacks
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".gotchas">陷阱（Gotchas）</a>
        <ul class="gotchas desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas/divide-by-zero.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Divide by Zero
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas/garbage-collection.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Garbage Collection
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas/scheduling.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Scheduling
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas/side-effect-ordering-in-function-call-expressions.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Function Call Side Effects
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/gotchas/recursion.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Recursion
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".where-next">下一步？（Where Next?）</a>
        <ul class="where-next desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/where-next.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
        </ul>
      </li>
      
      <li class="f5 w-100 hover-bg-light-gray hover-accent-color-light fw8">
        <a href="javascript:void(0)" class="js-toggle dib w-100 link mid-gray hover-accent-color-light pl2 pr2 pv2 " data-target=".appendices">附录（Appendices）</a>
        <ul class="appendices desktopmenu animated fadeIn list pl0 bg-light-gray dn">
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              概述（Overview）
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/ponypath.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              PONYPATH
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/lexicon.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Lexicon
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/symbol-lookup-cheatsheet.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Symbol Lookup Cheatsheet
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/keywords.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Keywords
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/examples.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Examples
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/whitespace.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Whitespace
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/compiler-args.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Compiler Arguments
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/memory-allocation.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Memory Allocation at Runtime
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/garbage-collection.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Garbage Collection with Pony-ORCA
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/platform-dependent-code.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Platform-dependent code
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/error-messages.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              A Short Guide to Pony Error Messages
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/annotations.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Program Annotations
            </a>
          </li>
          <li class="f6 fw4">
            <a href="/pony-tutorial/appendices/serialisation.html" class="db link hover-bg-gray hover-white pl3 pr2 pv2 black ">
              Serialisation
            </a>
          </li>
        </ul>
      </li>
  </ul>
</nav>

    </div>
    <div class="flex-l" id="the-body"><div class="order-2 w-100 w-20-l ph5-m ph0-l mb4 sticky dn db-l" id="context-menu"><div class="bg-light-gray pa3 nested-list-reset nested-copy-line-height nested-links">
    <p class="f5 b mb3">What's in this document</p>
      <nav id="TableOfContents">
  <ul>
    <li><a href="#条件判断conditionals">条件判断（Conditionals）</a></li>
    <li><a href="#一切皆表达式everything-is-an-expression">一切皆表达式（Everything is an expression）</a></li>
    <li><a href="#loops表达式loops">Loops表达式（Loops）</a>
      <ul>
        <li><a href="#while表达式while">While表达式（While）</a></li>
        <li><a href="#中止循环break">中止循环（Break）</a></li>
        <li><a href="#continue表达式">Continue表达式</a></li>
        <li><a href="#for表达式">For表达式</a></li>
        <li><a href="#重复执行表达式repeat">重复执行表达式（Repeat）</a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>




</div><div class="order-1 w-60-l mw9 ph0 ph5-ns mid-gray nested-copy-line-height no-underline nested-links nested-img nested-copy-seperator nested-blockquote mt0-ns" style="flex-grow:1;">
        <div class="order-0 mt4 w-100 center mw7" style="clear: both;">
          <a id="doc-menu-toggle" class="icon icon-menu" href="javascript:void(0)" onClick="hideShowDM()"></a><a id="context-menu-toggle" class="icon icon-menu" href="javascript:void(0)" onClick="hideShowCM()"></a></div>

        <div class="documentation-copy center mw7" id="content">
          <header class="mt4 w-100">
            <p class="f6 b helvetica tracked">
                
              表达式（EXPRESSIONS）
            </p>
            <h1 class="f1 athelas mb1">流程控制（Control Structures）</h1>
          </header>

          <main class="nested-copy-line-height lh-copy serif f4 nested-links nested-img mid-gray pr4-l"><!-- raw HTML omitted -->
<p>在程序开发过程中，你需要能够对条件做出判断，对集合进行遍历，或者重复执行一些逻辑。因此，流程控制必不可少。Pony具有你在其他语言中所熟悉的流程控制控制，例如<code>if</code>，<code>while</code>和<code>for</code>，但是在Pony中，它们的工作方式略有不同。</p>
<!-- raw HTML omitted -->
<h2 id="条件判断conditionals">条件判断（Conditionals）</h2>
<!-- raw HTML omitted -->
<p><code>if</code>是最简单的流程控制控制。它仅在条件为真时才允许您执行某些操作。在Pony中的用法：</p>
<pre><code class="language-pony" data-lang="pony">if a &gt; b then
  env.out.print(&quot;a is bigger&quot;)
end
</code></pre><!-- raw HTML omitted -->
<p><strong>可以像在C语言中那样使用整数和指针作为条件吗？</strong> 不行。在Pony中，<code>if</code>条件必须是布尔类型，即条件的返回值值始终为true或false。如果要判断数字<code>a</code>是否不为0，则需要明确的使用<code>a！= 0</code>。这个限制让Pony程序避免了潜在的类型错误。</p>
<!-- raw HTML omitted -->
<p>需要在条件失败时的执行一些逻辑，只需添加一个<code>else</code>：</p>
<pre><code class="language-pony" data-lang="pony">if a &gt; b then
  env.out.print(&quot;a is bigger&quot;)
else
  env.out.print(&quot;a is not bigger&quot;)
end
</code></pre><!-- raw HTML omitted -->
<p>通常，您想要检测和处理多种条件，可以嵌套<code>if</code>语句，但这有点丑陋：</p>
<pre><code class="language-pony" data-lang="pony">if a == b then
  env.out.print(&quot;they are the same&quot;)
else
  if a &gt; b then
    env.out.print(&quot;a is bigger&quot;)
  else
    env.out.print(&quot;b bigger&quot;)
  end
end
</code></pre><!-- raw HTML omitted -->
<p>作为替代方案，Pony提供了结合了<code>else</code>和<code>if</code>的<code>elseif</code>关键字。这与其他语言中<code>else if</code>相同，并且每个<code>if</code>可以有任意数量的<code>elseif</code>：</p>
<pre><code class="language-pony" data-lang="pony">if a == b then
  env.out.print(&quot;they are the same&quot;)
elseif a &gt; b then
  env.out.print(&quot;a is bigger&quot;)
else
  env.out.print(&quot;b bigger&quot;)
end
</code></pre><!-- raw HTML omitted -->
<p><strong>为什么不能像在C语言中那样用<code>else if</code>？为什么要用新的关键字？</strong> C和其他类似语言中的<code>if</code>和<code>else</code>之间的关系是模棱两可的。例如：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-C" data-lang="C"><span style="color:#75715e">// C code
</span><span style="color:#75715e"></span><span style="color:#66d9ef">if</span>(a)
  <span style="color:#66d9ef">if</span>(b)
    printf(<span style="color:#e6db74">&#34;a and b</span><span style="color:#ae81ff">\n</span><span style="color:#e6db74">&#34;</span>);
<span style="color:#66d9ef">else</span>
  <span style="color:#a6e22e">printf</span>(<span style="color:#e6db74">&#34;not a</span><span style="color:#ae81ff">\n</span><span style="color:#e6db74">&#34;</span>);
</code></pre></div><!-- raw HTML omitted -->
<p>上面的示例中，<code>else</code>到底归属于第一个还是第二个<code>if</code>有点让人困惑。实际上，<code>else</code>归属与<code>if(b)</code>，显然示例里面<code>else</code>语句本意是想归属于<code>if(a)</code>。Pony通过以不同的方式处理<code>if</code>和<code>else</code>来避免此类错误，那就是<code>elseif</code>。</p>
<!-- raw HTML omitted -->
<h2 id="一切皆表达式everything-is-an-expression">一切皆表达式（Everything is an expression）</h2>
<!-- raw HTML omitted -->
<p>Pony的流程控制与其他语言的最大区别在于，在Pony中，一切都是表达式。在C++和Java这样的语言中，<code>if</code>是语句，而不是表达式。这意味着您不能在表达式中包含<code>if</code>，而必须有一个单独的条件运算符<code>？</code>（三目运算符 <code>a ? b : c</code>）。</p>
<!-- raw HTML omitted -->
<p>在Pony中，不存在语句的概念，只有表达式，所有东西都有返回一个值。if表达式是一个求值过程。<code>for</code>循环表达式也（稍后再讨论）也是如此。</p>
<!-- raw HTML omitted -->
<p>这意味着您可以在计算中直接使用<code>if</code>：</p>
<pre><code class="language-pony" data-lang="pony">x = 1 + if lots then 100 else 2 end
</code></pre><!-- raw HTML omitted -->
<p>通过变量 <strong>lots</strong> ，为 <strong>x</strong> 赋值为3或101。</p>
<!-- raw HTML omitted -->
<p>如果<code>if</code>的<code>then</code>和<code>else</code>分支产生不同的类型，则<code>if</code>返回两者的 <strong>联合类型（union）</strong> 。</p>
<pre><code class="language-pony" data-lang="pony">var x: (String | Bool) =
  if friendly then
    &quot;Hello&quot;
  else
    false
  end
</code></pre><!-- raw HTML omitted -->
<p><strong>但是<code>if</code>表达式没有<code>else</code>呢？</strong> 任何不存在的<code>else</code>分支都会默认返回<code>None</code>（None是基元类的实例）。</p>
<pre><code class="language-pony" data-lang="pony">var x: (String | None) =
  if friendly then
    &quot;Hello&quot;
  end
</code></pre><!-- raw HTML omitted -->
<p><code>if</code>表达式的规则也适用于循环。我们看一下Pony的循环是什么样的：</p>
<pre><code class="language-pony" data-lang="pony">actor Main
  new create(env: Env) =&gt;
    var x: (String | None) =
      for name in [&quot;Bob&quot;; &quot;Fred&quot;; &quot;Sarah&quot;].values() do
        name
      end
    match x
    | let s: String =&gt; env.out.print(&quot;x is &quot; + s)
    | None =&gt; env.out.print(&quot;x is None&quot;)
    end
</code></pre><!-- raw HTML omitted -->
<p><strong>x</strong> 会被赋值为<code>Sarah</code>，它是循环列表中的最后一个元素。如果循环直接跳出了（0次迭代），那么__x__ 的值就是<code>else</code>表达式的返回值。如果没有<code>else</code>块，则该值为<code>None</code>。</p>
<pre><code class="language-pony" data-lang="pony">actor Main
  new create(env: Env) =&gt;
    var x: (String | None) =
      for name in Array[String].values() do
        name
      else
        &quot;no names!&quot;
      end
    match x
    | let s: String =&gt; env.out.print(&quot;x is &quot; + s)
    | None =&gt; env.out.print(&quot;x is None&quot;)
    end
</code></pre><!-- raw HTML omitted -->
<p>_<strong>x</strong> 的值在这里是&quot;no names!&quot;。</p>
<pre><code class="language-pony" data-lang="pony">actor Main
  new create(env: Env) =&gt;
    var x: (String | None) =
      for name in Array[String].values() do
        name
      end
    match x
    | let s: String =&gt; env.out.print(&quot;x is &quot; + s)
    | None =&gt; env.out.print(&quot;x is None&quot;)
    end
</code></pre><!-- raw HTML omitted -->
<p>最后，<strong>x</strong> 的值是<code>None</code>。</p>
<!-- raw HTML omitted -->
<h2 id="loops表达式loops">Loops表达式（Loops）</h2>
<!-- raw HTML omitted -->
<p><code>if</code>允许您选择要执行的操作，但是不止一次想要循环就可以执行其他操作。</p>
<!-- raw HTML omitted -->
<h3 id="while表达式while">While表达式（While）</h3>
<!-- raw HTML omitted -->
<p>Pony的while循环与其他语言非常相似。条件表达式将被求值，如果为真，将执行一次循环内的代码，完成后，我们将再次评估条件，并继续进行直到条件不成立为止。</p>
<!-- raw HTML omitted -->
<p>这是一个打印数字1到10的示例：</p>
<pre><code class="language-pony" data-lang="pony">var count: U32 = 1

while count &lt;= 10 do
  env.out.print(count.string())
  count = count + 1
end
</code></pre><!-- raw HTML omitted -->
<p>就像if表达式，while也是表达式一样。返回值是最后循环执行时的表达式返回值。在这个例子中，当count递增到11时，也就是<code>count = count + 1</code>的返回值值。Pony会将最后一次正确执行循环的 <em>旧值（old）</em> 返回，最终<code>while</code>循环将返回10。</p>
<!-- raw HTML omitted -->
<p><strong>但是如果<code>while</code>在第一次判断就为假，那不久就不会执行循环吗？</strong> 在Pony中，<code>while</code>表达式也可以有一个<code>else</code>块，在没有提供<code>else</code>表达式时，Pony的<code>else</code>块会提供一个默认值<code>None</code>。注意：只有在第一次评估就为false时（也就是while循环体没机会执行时），才会返回<code>else</code>表达式的值。</p>
<!-- raw HTML omitted -->
<p><strong>所以这就像Python中<code>while</code>循环中的<code>else</code>块吗？</strong> 这是非常不同的。在Python中，<code>else</code>在<code>while</code>完成时运行。在Pony中，<code>else</code>仅在<code>while</code>没有机会运行时才执行。</p>
<!-- raw HTML omitted -->
<h3 id="中止循环break">中止循环（Break）</h3>
<!-- raw HTML omitted -->
<p>有时，您希望在循环中途停止并跳出。 Pony为此使用了关键字<code>break</code>，它与C ++，C＃和Python等语言中的关键字非常相似。</p>
<!-- raw HTML omitted -->
<p>break会立即从它所在的最里面的循环中退出。由于循环必须返回一个值，break可以采用一个表达式。这是可选的，如果错过了，则返回<code>else</code>块中的值。</p>
<!-- raw HTML omitted -->
<p>让我们举个例子。假设您要浏览从某处获取的名称列表，查找<code>Jack</code>或<code>Jill</code>。如果这两个都没有出现，则只使用您的姓氏，如果根本不使用任何名字，则使用<code>Herbert</code>。</p>
<pre><code class="language-pony" data-lang="pony">var name =
  while moreNames() do
    var name' = getName()
    if name' == &quot;Jack&quot; or name' == &quot;Jill&quot; then
      break name'
    end
    name'
  else
    &quot;Herbert&quot;
  end
</code></pre><!-- raw HTML omitted -->
<p>因此，首先我们要询问是否还有其他名字。如果有的话，我们得到这个名字，看看它是<code>Jack</code>还是<code>Jill</code>，如果符合条件，将跳出循环，将找到的名字递回。如果没有，我们再试一次。</p>
<!-- raw HTML omitted -->
<p><code>name</code>行出现在循环的末尾，因此如果找不到<code>Jack</code>或<code>Jill</code>，返回值最后一次迭代的名字。</p>
<!-- raw HTML omitted -->
<p>如果一开始就发现根本没有可用名，则返回<code>else</code>块提供的<code>Herbert</code>值。</p>
<!-- raw HTML omitted -->
<p><strong>可以从多层嵌套的循环中直接跳出吗？就像Java的break那样</strong> 没有，Pony不支持。这是糟糕的逻辑表达方式，当你遇到需要从多层嵌套循环中直接跳出的情况，你应该重构你的代码或使用辅助函数。</p>
<!-- raw HTML omitted -->
<h3 id="continue表达式">Continue表达式</h3>
<!-- raw HTML omitted -->
<p>有时，您希望在一次循环迭代中中途停止，然后进行下一次循环。像其他语言一样，Pony为此使用了<code>continue</code>关键字。</p>
<!-- raw HTML omitted -->
<p><code>continue</code>将停止执行它所在的最内层循环的当前迭代，并评估条件以准备进行下一次迭代。</p>
<!-- raw HTML omitted -->
<p>如果在循环的最后一次迭代中<code>continue</code>被触发了，那么我们循环就不会有返回值。在这种情况下，将返回<code>else</code>表达式的值。与<code>if</code>表达式一样，如果未提供<code>else</code>表达式，则返回<code>None</code>。</p>
<!-- raw HTML omitted -->
<p><strong>Pony的<code>continue</code>可以直接跳到一个外部嵌套循环中继续执行吗？就像Java的<code>continue</code>。</strong> 不行，Pony不支持。如果需要跳转到外层循环继续执行，说明你的逻辑应该重构了。</p>
<!-- raw HTML omitted -->
<h3 id="for表达式">For表达式</h3>
<!-- raw HTML omitted -->
<p>在Pony中需要便利集合，可以使用<code>for</code>表达式。当与集合一起使用时，这非常类似于C＃中的<code>foreach</code>，Python中的<code>for..in</code>和Java中的<code>for</code>。它与C和C++中的<code>for</code>非常不同。</p>
<!-- raw HTML omitted -->
<p>Pony的<code>for</code>循环使用迭代器遍历集合。在每次迭代中，都会询问迭代器是否还有要处理的元素。</p>
<!-- raw HTML omitted -->
<p>例如，打印出数组中的所有字符串：</p>
<pre><code class="language-pony" data-lang="pony">for name in [&quot;Bob&quot;; &quot;Fred&quot;; &quot;Sarah&quot;].values() do
  env.out.print(name)
end
</code></pre><!-- raw HTML omitted -->
<p>注意在数组上调用<code>values()</code>，是因为循环需一个迭代器。</p>
<!-- raw HTML omitted -->
<p>迭代器没有特定的类型需求，但需要提供以下接口方法：</p>
<pre><code class="language-pony" data-lang="pony">  fun has_next(): Bool
  fun next(): T?
</code></pre><!-- raw HTML omitted -->
<p>其中<code>T</code>是集合中对象的类型。除非您需要编写自己的迭代器，否则无需担心。要使用现有的集合（例如标准库中提供的集合），您只需使用<code>for</code>即可。如果你编写了自己的迭代器，请使用<code>结构化多态</code>的方式满足<code>接口</code>需求，你的迭代器无需特定的类型声明。</p>
<!-- raw HTML omitted -->
<p>您可以认为上述示例等效于：</p>
<pre><code class="language-pony" data-lang="pony">let iterator = [&quot;Bob&quot;; &quot;Fred&quot;; &quot;Sarah&quot;].values()
while iterator.has_next() do
  let name = iterator.next()?
  env.out.print(name)
end
</code></pre><!-- raw HTML omitted -->
<p>请注意，变量 <strong>name</strong> 使用 <em>let</em> 声明，所以不能在循环内为其重新赋值。</p>
<!-- raw HTML omitted -->
<p><strong>我可以使用break并继续使用<code>for</code>循环吗？</strong> 可以的，<code>for</code>循环可以附加<code>else</code>表达式，并且可以像<code>while</code>一样使用<code>break</code>和<code>continue</code>。</p>
<!-- raw HTML omitted -->
<h3 id="重复执行表达式repeat">重复执行表达式（Repeat）</h3>
<!-- raw HTML omitted -->
<p>Pony提供的最后一个循环表达式是<code>repeat``until</code>。在这里，我们评估循环中的表达式，然后评估条件表达式，看看是否完成或应该再次处理。</p>
<!-- raw HTML omitted -->
<p>这与C++，C＃和Java中的<code>do``while</code>类似，不同之处在于终止条件是相反的，即那些语言在条件表达式为false时终止循环，而Pony在条件表达式为true时终止循环。</p>
<!-- raw HTML omitted -->
<p>Pony中的<code>while</code>和<code>repeat</code>的区别是：</p>
<!-- raw HTML omitted -->
<!-- raw HTML omitted -->
<ol>
<li><code>repeat</code>表达式至少会执行一次，而使用<code>while</code>则可能一次都不执行。</li>
<li>结束条件相反。</li>
</ol>
<!-- raw HTML omitted -->
<p>加入我们正在尝试执行一些逻辑，并且想不断重复直到满足条件为止：</p>
<pre><code class="language-pony" data-lang="pony">actor Main
  new create(env: Env) =&gt;
    var counter = U64(1)
    repeat
      env.out.print(&quot;hello!&quot;)
      counter = counter + 1
    until counter &gt; 7 end
</code></pre><!-- raw HTML omitted -->
<p>就像<code>while</code>循环一样，<code>repeat</code>循环返回的值就是上一次迭代时循环内表达式的值，并且可以使用<code>break</code>和<code>continue</code>。</p>
<!-- raw HTML omitted -->
<p><strong>由于至少要执行一次重复循环，还有必要给它提供一个else表达式吗？</strong> 是的，您可能需要这样做。 如果<code>repeat</code>循环的最后一次迭代中触发了<code>continue</code>那就需要从某个地方获取一个值，这就需要使用<code>else</code>表达式。</p>
</main>
        </div>
        <div id="search-results" class="center mw7 dn"></div>
      </div>
    </div>
  </article>

    </main>
    

<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.15.6/languages/pony.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/lunr.js/2.3.5/lunr.min.js"></script>

<script async defer src="https://buttons.github.io/buttons.js"></script>

<script>
  var toggleBtns = document.getElementsByClassName('js-toggle')
  for (var i = 0; i < toggleBtns.length; i++) {
    toggleBtns[i].addEventListener('click', toggleClass, false)
  }

  var myToggleBtns = document.getElementsByClassName('hide-show-toggle')
  for (var i = 0; i < myToggleBtns.length; i++) {
    myToggleBtns[i].addEventListener('click', hideShow, false)
  }

function hideShowDM() {
  var menu = document.getElementById("doc-menu")
  var thebody = document.getElementById("the-body")
  if (window.getComputedStyle(menu).display == "none") {
    menu.style.display = "block";
    thebody.style.left = "300px";
  } else {
    menu.style.display = "none";
    thebody.style.left = "0px";
  }
}

function hideShowCM() {
  var menu = document.getElementById("context-menu")
  if (window.getComputedStyle(menu).display == "none") {
    menu.style.display = "block";
  } else {
    menu.style.display = "none";
  }
}

function toggleClass() {
  
  var content = this.dataset.target.split(' ')
  
  var mobileCurrentlyOpen = document.querySelector('.mobilemenu:not(.dn)')
  var desktopCurrentlyOpen = document.querySelector('.desktopmenu:not(.dn)')
  var desktopActive = document.querySelector('.desktopmenu:not(.dn)')

  
  for (var i = 0; i < content.length; i++) {
    var matches = document.querySelectorAll(content[i]);
    
    [].forEach.call(matches, function(dom) {
        dom.classList.contains('dn') ?
        dom.classList.remove('dn') :
        dom.classList.add('dn');
         return false;
       });
        
      if (mobileCurrentlyOpen) mobileCurrentlyOpen.classList.add('dn')
      if (desktopCurrentlyOpen) desktopCurrentlyOpen.classList.add('dn')
      if (desktopActive) desktopActive.classList.remove('db')

    }
  }

var Pony = {};


Pony.Search = (function() {
  var that = {}
  that.lunrIndex = undefined;
  that.pages = [];

  that.doSearch = function(query) {
    var resultsContainer = $('#search-results');
    var contentContainer = $('#content');
    
    var results = this.lunrIndex.search(query).map(function(result) {
      
        return {
            page: that.pages[result.ref],
            metadata: result.matchData.metadata
        };
    });

    
    resultsContainer.empty();
    resultsContainer.append(
        $("<header>", {class: "mt4 w-100"}).append(
            $("<p>", {class: "f6 b helvetica tracked", text: "SEARCH RESULTS"}))
    );
    var resList = $("<ul>", {id: "search-result-list"});

    
    results.slice(0, 100).forEach(function(result) {
        var res = $("<li>");
        var div = $("<div>", {class: "search-result"});
        div.append($("<a>", {
          href: result.page.uri,
          text: result.page.title,
          class: "search-result-title"
        }));
        var p = $("<p>", {
            class: "search-result-summary"
        });
        var highlighted = that.highlightResult(result.page.summary, result.metadata);
        p.append(highlighted);
        div.append(p);
        res.append(div);
        resList.append(res);
    });
    resultsContainer.append(resList);

    
    contentContainer.addClass("dn");
    resultsContainer.removeClass("dn");
  };

  that.highlightResult = function(text, metadata) {
      var span = $("<span>");
      for (var key in metadata) {
        var summary_metadata = metadata[key]["summary"];
        if (summary_metadata !== undefined && summary_metadata["position"] !== undefined) {
            var position_metadata = summary_metadata["position"];
            var last_pos = 0;
            summary_metadata["position"].forEach(function(elem) {
                span.append(
                    $("<span>", {text: text.slice(last_pos, elem[0])})
                );
                span.append(
                    $("<span>", {
                        class: "highlighted",
                        text: text.slice(elem[0], elem[0] + elem[1])})
                );
                last_pos = elem[0] + elem[1];
            });
            span.append(
                $("<span>", {text: text.slice(last_pos, text.length)})
            );
        } else {
          span.text(text);
        }
      }
      return span;
  };

  that.initLunr = function(onSuccess) {
      $.getJSON("/index.json")
        .done(function(index) {
           
           that.pages = index;
           that.lunrIndex = lunr(function() {
             this.metadataWhitelist = ['position']; 
             this.field("title", { boost: 10 });
             this.field("tags", { boost: 5 });
             this.field("categories", { boost: 5 });
             this.field("content");
             this.field("summary", {boost: 0});
             this.ref("i");

             index.forEach(function (page, idx) {
                 page["i"] = idx;
                 this.add(page)
               },
               this
             );
           });
           onSuccess();
        })
        .fail(function(jqxhr, textStatus, error) {
          var err = textStatus + ", " + error;
          console.error("Error getting search index file:", err);
        });
    }
  that.setUpSearchUI = function() {
    $('#search-box').keyup(function() {
        var query = $(this).val();
        if (query.length < 2) {
            if (query.length == 0) {
                $('#content').removeClass('dn');
                $('#search-results').empty().addClass('dn');
            }
            return;
        }
        if (that.lunrIndex === undefined) {
            that.initLunr(function () {
              that.doSearch(query);
            });
        } else {
            that.doSearch(query);
        }
    });
  }
  return that;
})();




$(document).ready(function() {
  Pony.Search.setUpSearchUI();
});
</script>

  </body>
</html>
